﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Microsoft.Win32;

namespace E_mail
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const string ContactFile = "Contacts.csv";
        private readonly AccountPropertis _propertis = new AccountPropertis();
        private readonly ObservableCollection<Contact> _selectedContacts = new ObservableCollection<Contact>();
        private ObservableCollection<Contact> _allContacts;
        private MailMessage _message;
        private SmtpClient _client;
        private WindowSending _sendScreen;// = new WindowSending();

        public MainWindow()
        {
            InitializeComponent();
        }

        #region Form close

        private void Window_Closing(object sender, CancelEventArgs e)
        {
//            if (_propertis != null)
//                _propertis.Save();
//            
        }

        private void MenuItem_Close_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Btn_Cancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        #endregion

        #region Wysylanie wiadomości

        private void btn_Send_Click(object sender, RoutedEventArgs e)
        {
            _message = new MailMessage
                           {
                               From = new MailAddress(Environment.MachineName + "@" + Environment.UserName + ".pl")
                           };

            #region Adresat wiadomosci

            if (String.IsNullOrEmpty(_textBox_To.Text))
            {
                MessageBox.Show("Musisz podać adresata", "Info", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            string[] To = GetaddressFromTextBox().Split(';');

            foreach (String item in To)
            {
                if (item.Length > 1)
                    _message.To.Add(item);
            }

            #endregion

            #region Temat wiadomosci

            if (String.IsNullOrEmpty(textBox_subject.Text))
            {
                MessageBoxResult resoult = MessageBox.Show("Czy chcesz wysłać wiadomość bez tematu?", "temat wiadomości",
                                                           MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (resoult == MessageBoxResult.No)
                    return;
            }
            _message.Subject = textBox_subject.Text;

            #endregion

            #region Załącznik

            GetAttachments(_message.Attachments);

            #endregion

            #region Wysyłanie emaila

            if (_propertis.dane == null)
            {
                var resoult =
                    MessageBox.Show(
                        "Nie ma skonfigurowanych parametrów serwera wychodzącego.\nChcesz to zrobić teraz?", "Info",
                        MessageBoxButton.YesNo);
                if (resoult == MessageBoxResult.No)
                    return;

                var t = new WindowPropertis(_propertis).ShowDialog();

                if (t == null || t == false)
                    return;
            }


            if (_propertis.dane == null || string.IsNullOrEmpty(_propertis.dane.ServerAdress))
            {
                MessageBoxResult resoult =
                    MessageBox.Show(
                        "Nie ma skonfigurowanych parametrów serwera wychodzącego.\nChcesz to zrobić teraz?", "Info",
                        MessageBoxButton.YesNo);
                if (resoult == MessageBoxResult.No)
                    return;
                else
                {
                    bool? t = new WindowPropertis(_propertis).ShowDialog();

                    if (t == null || t == false)
                        return;
                }
            }

            if (String.IsNullOrEmpty(_propertis.Password))
            {
                bool? t = new WindowPassword(_propertis).ShowDialog();
                if (t != null && t == false)
                {
                    return;
                }
            }


            if (_propertis.dane != null)
            {
                _client = new SmtpClient(_propertis.dane.ServerAdress)
                             {
                                 UseDefaultCredentials = false,
                                 Credentials = new NetworkCredential(_propertis.dane.UserName, _propertis.Password),
                                 Port = _propertis.dane.Port,
                                 EnableSsl = true,
                                 DeliveryMethod = SmtpDeliveryMethod.Network
                             };

                _client.SendCompleted += new SendCompletedEventHandler(Client_SendCompleted);
                try
                {
                    _client.SendAsync(_message, "Koniec wysyłania");
                    if (_sendScreen == null)
                    {
                        _sendScreen = new WindowSending();
                        _sendScreen.Show();
                    }
                    else
                    {
                        _sendScreen.Show();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return;
                }
            }
        }

        private void Client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            if(_sendScreen!=null)
            {
                if(_sendScreen.IsLoaded)
                    _sendScreen.Close();       
            }

            MessageBox.Show("Wiadomość wysłana.");
            ClearAll();
            btn_Cancel.Focus();
        }

        #endregion

        #endregion

        #region Załączniki

        private void GetAttachments(AttachmentCollection ac)
        {
            foreach (ListViewItem item in ListView_attachments.Items)
            {
                var att = new Attachment(item.Content.ToString());
                ac.Add(att);
            }
        }

        private void Btn_RemoveAttachment_Click(object sender, RoutedEventArgs e)
        {
            IList l = ListView_attachments.SelectedItems;
            Object t;
            for (int i = l.Count; l.Count > 0;i++ )
            {
                t = l[i-1];
                ListView_attachments.Items.Remove(t);
            }
        }

        private void Btn_Addattachments_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog();
            var resoult = dlg.ShowDialog();

            if (resoult == false)
                return;

            foreach (var item in dlg.FileNames)
            {
                ListView_attachments.Items.Add(new ListViewItem {Content = item});
            }
        }

        #endregion

        #region Pobranie adresów 

        private string GetaddressFromTextBox()
        {
            _textBox_To.Text.Replace(',', ';');
            _textBox_To.Text.Replace(' ', ';');
            return _textBox_To.Text;
        }

        #endregion

        #region Windows Loaded

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                string[] t = Environment.GetCommandLineArgs();

                if (t.Length > 1)
                {
                    for (int i = 1; i < t.Length; i++)
                    {
                        ListView_attachments.Items.Add(new ListViewItem {Content = t[i]});
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
                Close();
            }

            try
            {
                //wczytywnaie danych z pliku konfiguracyjnego.
                _propertis.LoadAccountPropertis();
                MenuItemAddToRegistry.IsChecked = _propertis.dane.AddedToMenu;
            }
            catch (FileNotFoundException fileNotFoundException)
            {
                MessageBox.Show(fileNotFoundException.ToString());
                Close();
            }

            if (!string.IsNullOrEmpty(_propertis.dane.KontaktsFile))
            {
                LoadContacts();
            }
            
            _textBox_To.ItemsSource = _allContacts;

            SystemMenu.Added += new EventHandler(SystemMenu_Added);
            SystemMenu.Removed += new EventHandler(SystemMenu_Removed);

            _textBox_To.Focus();
        }
        #endregion

        #region Okno kontaktow

        private void btn_To_Click(object sender, RoutedEventArgs e)
        {
            LoadContacts();
            bool? result = new WindowContacts(_allContacts, _selectedContacts, _propertis.dane).ShowDialog();
            if (result == false)
                return;
            foreach (var item in _selectedContacts)
            {
                _textBox_To.Text += item.Email + ";";
            }
        }

        #region Wczytywanie Listy kontaktów

        private void LoadContacts()
        {
            if (_allContacts == null)
            {
                _allContacts = new ObservableCollection<Contact>();
                List<string[]> g;
                g =
                    CSVParser.LoadFile(!String.IsNullOrEmpty(_propertis.dane.KontaktsFile)
                                           ? _propertis.dane.KontaktsFile
                                           : ContactFile);
                FillContactList(g);
            }
        }

        #endregion

        #region Wczytanie listy kontaktów z pliku

        private void FillContactList(IList<string[]> g)
        {
            for (int i = 1; i < g.Count; i++)
            {
                var tmp = g[i];
                try
                {
                    if (!String.IsNullOrEmpty(tmp[28]))
                        _allContacts.Add(new Contact(tmp[28], tmp[0], tmp[26]));
                }
                catch (IndexOutOfRangeException)
                {
                }
            }
        }

        #endregion

        #endregion

        #region Czyszczenie kontrolek po wysłaniu emaila

        private void ClearAll()
        {
            _textBox_To.Text = "";
            textBox_subject.Text = "";
            _selectedContacts.Clear();
            ListView_attachments.Items.Clear();
            TextBox_EmailContent.Text = "";
        }

        #endregion

        #region Filtrowanie listy odbiorców

        private void _textBox_To_KeyUp(object sender, KeyEventArgs e)
        {
            //CollectionViewSource.GetDefaultView(_allContacts).Refresh();
            //_textBox_To.IsDropDownOpen = true;
        }

        #endregion

        #region Dodawanie do menu sendTo

        private void MenuItem_AddToMenu_Click(object sender, RoutedEventArgs e)
        {
            SystemMenu.Add();
            _propertis.dane.AddedToMenu = true;
            if (Errors.Exceptions.Count > 0)
            {
                MessageBox.Show(Errors.NewException.Message);
            }
            else
            {
                return;
            }
        }

        private void SystemMenu_Added(object sender, EventArgs e)
        {
            MessageBox.Show("Dodano odnościk do menu systemowego.");
        }

        private void MenuItem_RemoveFromMenu_Click(object sender, RoutedEventArgs e)
        {
            SystemMenu.Remove();
            _propertis.dane.AddedToMenu = false;
        }

        private void SystemMenu_Removed(object sender, EventArgs e)
        {
            MessageBox.Show("Usnięto skrót do programu");
        }

        #endregion
    }
}